
/*
 * @Date         : 2021-01-24 16:06:13
 * @LastEditors  : LiZhenglin
 * @LastEditTime : 2021-02-18 18:02:06
 * @FilePath     : \QianjiAutoRecord\monitor\ActivityMonitor.js
 */

let _debugInfo = typeof debugInfo === 'undefined' ? (v) => console.verbose(v) : debugInfo

// const myUtil = require("../utils/Util.js")
const pageDict = require("../resources/pageDict/PageDict.js")
const miniFloaty = require("../layout/MiniFloaty.js")

const aliMonitor = require("./AliMonitor.js")
const wechatMonitor = require("./WechatMonitor.js")
const meituanMonitor = require("./MeituanMonitor.js")

let ActivityMonitor = function () {
    this.unrelatedPageTimeOutSecond = 10000      // 记账流程中，无关页面所在时间超过该值则取消记账
    this.analyzing = false
    this.pageRecordIdx = 0
    this.pageRecord = ["undefined", null, null, null, null, null, null, null, null, null,
                        null, null, null, null, null, null, null, null, null, null]
                        
    this.showLog = true
    this.debugInfo = function (content) {
        this.showLog && _debugInfo(content)
    }
}

ActivityMonitor.prototype.init = function(global_config, record) {
    this.global_config = global_config
    this.record = record
    
}

ActivityMonitor.prototype.monitor = function (enable_feature_list) {
    this.debugInfo("开始监控屏幕")
    let _this = this
    let package_list = []
    let activity_page_name_dict = {}
    let default_page = {}
    
    // 记录所有 package，及其对应的默认页面；记录 activity 对应的页面
    for(var key in pageDict) {
        let package_name = pageDict[key]["package_name"]
        let is_default_page = pageDict[key]["default_page"]
        let activity = pageDict[key]["activity"]
        // package 列表
        if(!myUtil.inList(package_name, package_list)) {
            package_list.push(package_name)
        }
        // package 对应的默认页面
        if(is_default_page) {
            default_page[package_name] = key
        }
        // activity 对应的页面列表
        if(activity_page_name_dict[activity] == null){
            activity_page_name_dict[activity] = [key]
        } else {
            activity_page_name_dict[activity].push(key)
        }     
    }

    threads.start(function () {
        toast("开始自动记账")
        while(true) {
            if(!device.isScreenOn()) {  // 屏幕熄灭，检测间隔 3000ms
                sleep(3000) 
            }
            else {
                let current_page = myUtil.currentActivity2PageName(pageDict, package_list, activity_page_name_dict, default_page)
                // 进入一个新的已知页面
                if(current_page != _this.pageRecord[_this.pageRecordIdx % _this.pageRecord.length]) {
                    _this.pageRecord[(++_this.pageRecordIdx) % _this.pageRecord.length] = current_page
                    _this.debugInfo("进入新页面：" + current_page)
                    // 未分析中，且当前页面在启用特性中
                    if(!_this.analyzing && myUtil.inPageList(current_page, enable_feature_list)){
                        _this.analyzing = true
                        _this.analyze(current_page)
                    }
                }
            }
        }
    })
}

ActivityMonitor.prototype.analyze = function (page_name) {
    let _this = this
    threads.start(function() {
        if(!myUtil.inPageList(page_name, ["支付宝付款框", "微信指纹支付", "微信密码支付", "淘宝付款框"])) // 页面没有悬浮窗权限
            miniFloaty.init()
        toast("检测到" + page_name)
        _this.debugInfo("检测到" + page_name + "，开始分析")

        if(myUtil.inPageList(page_name, ["微信发红包"]))            wechatMonitor.sendWechatRedBag(_this)
        else if(myUtil.inPageList(page_name, ["微信收红包"]))       wechatMonitor.receiveWechatRedBag(_this)
        else if(myUtil.inPageList(page_name, ["微信发转账"]))       wechatMonitor.transOutWechat(_this)
        else if(myUtil.inPageList(page_name, ["微信收转账"]))       wechatMonitor.transInWechat(_this)
        else if(myUtil.inPageList(page_name, ["微信密码支付", "微信指纹支付"]))
                                                                   wechatMonitor.activePayWechat(_this)
        else if(myUtil.inPageList(page_name, ["微信付款码"]))       wechatMonitor.passivePayWechat(_this)
        else if(myUtil.inPageList(page_name, ["支付宝付款框"]))     aliMonitor.activePayAli(_this)
        else if(myUtil.inPageList(page_name, ["支付宝付款码"]))     aliMonitor.passivePayAli(_this)
        else if(myUtil.inPageList(page_name, ["淘宝付款框"]))       aliMonitor.taobaoPay(_this)
        else if(myUtil.inPageList(page_name, ["美团订单页"]))       meituanMonitor.activePayMeituan(_this)
        miniFloaty.disAppear()

        _this.analyzing = false
    })
}

ActivityMonitor.prototype._save = function (type, money, account, remark, target) {
    if(!myUtil.isEmpty(this.global_config["remark_prefix"]))     remark = this.global_config["remark_prefix"] + remark
    if(!myUtil.isEmpty(this.global_config["remark_suffix"]))     remark = remark + this.global_config["remark_suffix"]
    
    if(money == 0 || money == "0.00") {
        this.debugInfo("获取金额为0，不记账\n" + message)
        miniFloaty.disAppear()
    } else {
        let message = "类型：" + type + "\n"
                    + "金额：" + money + "\n"
                    + "账户：" + account + "\n"
                    + "备注：" + remark
        this.debugInfo("分析页面获取：\n" + message)
        miniFloaty.disAppear()
        this.analyzing = false

        if(myUtil.isEmpty(target))  target = "未识别目标，统一记录"
        
        this.record.construct(type, money, account, remark, target, this.global_config)
        this.record.record()
    }
}

ActivityMonitor.prototype._cancel = function () {
    let message = "取消记账！！！"
    toast(message)
    this.debugInfo(message)
    miniFloaty.disAppear()
    this.analyzing = false
}

let pre_s = ""
ActivityMonitor.prototype._preprocess = function (page, related_page, timeCnt) {
    if(timeCnt == 1) {      // 超时取消
        this.debugInfo("操作超时")
        this._cancel()
        return 0
    }
    
    let s = ""
    // 处于无关界面
    if(!myUtil.inPageList(page, related_page)) {
        if(timeCnt > 0) timeCnt -= 1
        
        s = s + currentPackage() + " || " + currentActivity() + " || "
        let w = textStartsWith("").find()
        for(var i=0; i<w.length; ++i) {
            s = s + w[i].text()
            if(!myUtil.isEmpty(w[i].id())) {
                s = s + "|" + w[i].id()
            }
            s = s + " || "
        }

        if(pre_s != s) {
            pre_s = s
            console.log(s)
        }
    }else{
        timeCnt = this.unrelatedPageTimeOutSecond / 100
    }
    return timeCnt
}

module.exports = new ActivityMonitor()